<template>
	<view class="uni-container">
		<uni-forms ref="form" v-model="formData" :rules="rules" validateTrigger="bind" @submit="submit">
			<uni-forms-item name="username" label="学号/工号">
				<input placeholder="请输入学号/工号" @input="binddata('username', $event.detail.value)" class="uni-input-border" :value="formData.username" />
			</uni-forms-item>
			<uni-forms-item name="nickname" label="姓名">
				<input placeholder="请输入姓名" @input="binddata('nickname', $event.detail.value)" class="uni-input-border" :value="formData.nickname" />
			</uni-forms-item>
			<uni-forms-item name="year" label="入学/入职年份">
				<el-date-picker v-model="formData.year" type="year" value-format="yyyy" format="yyyy 年"   placeholder="选择入学/入职年份" style="width: 100%;"  ></el-date-picker>
			</uni-forms-item>
			<uni-forms-item name="role" label="角色列表">
				<uni-data-checklist multiple v-if="roles.length" :value="formData.role" :range="roles" @change="binddata('role', $event.detail.value)"></uni-data-checklist>
				<view v-else class="uni-form-item-empty">
					暂无
				</view>
			</uni-forms-item>
			<uni-forms-item name="college" label="学院">
				<uni-data-checklist v-if="colleges.length" :value="formData.college" :range="colleges" @change="binddata('college', $event.detail.value)"></uni-data-checklist>
				<view v-else class="uni-form-item-empty">
					暂无
				</view>
			</uni-forms-item>
			<uni-forms-item name="mobile" label="手机号">
				<input placeholder="手机号" @input="binddata('mobile', $event.detail.value)" class="uni-input-border" :value="formData.mobile" />
			</uni-forms-item>
			<uni-forms-item name="email" label="邮箱">
				<input placeholder="邮箱" @input="binddata('email', $event.detail.value)" class="uni-input-border" :value="formData.email" />
			</uni-forms-item>
			<uni-forms-item name="status" label="是否启用">
				<switch v-if="Number(formData.status) <= 1" @change="binddata('status', $event.detail.value)" :checked="formData.status" />
				<view v-else class="uni-form-item-empty">{{formData.status}}</view>
			</uni-forms-item>
			<view class="uni-button-group">
				<button style="width: 100px;" type="primary" class="uni-button" @click="submitForm">提交</button>
				<navigator url="/pages/system/user/list" style="margin-left: 15px;"><button style="width: 100px;" class="uni-button">返回</button></navigator>
				<button style="width: 100px;margin-left: 15px;" type="warn" class="uni-button" @click="resetPassword">重置密码</button>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import validator from '@/js_sdk/validator/uni-id-users.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'uni-id-users';

	function getValidator(fields) {
		let reuslt = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				reuslt[key] = validator[key]
			}
		}
		return reuslt
	}

	export default {
		data() {
			return {
				formData: {
					"username": "",
					"nickname": "",
					"year":"",
					"role": [],
					"college": [],
					"mobile": "",
					"email": "",
					"status": false //默认开启
				},
				rules: {
					...getValidator(["username", "nickname", "role", "college", "mobile", "email"]),
					"status": {
						"rules": [{
							"format": "bool"
						}]
					}
				},
				roles: [],
				colleges:[]
			}
		},
		onLoad(e) {
			const id = e.id
			this.formDataId = id
			this.getDetail(id)
			this.loadroles()
			this.loadcolleges()
		},
		methods: {
			/**
			 * 触发表单提交
			 */
			submitForm(form) {
				this.$refs.form.submit();
			},
			
			/**
			 * 触发重置密码提交
			 */
			resetPassword(){
				uni.showLoading({
					title: '重置中...',
					mask: true
				})
				// 使用 uni-clientDB 提交数据
				this.$request('user/resetPassword', this.formDataId)
				.then((res) => {
					uni.showToast({
						title: "密码初始化为123456"
					})
					setTimeout(() => uni.navigateTo({
						url: '/pages/system/user/list'
					}), 1000)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
				
			/**
			 * 表单提交
			 * @param {Object} event 回调参数 Function(callback:{value,errors})
			 */
			submit(event) {
				const {
					value,
					errors
				} = event.detail
				console.info(event.detail.value)
				// 表单校验失败页面会提示报错 ，要停止表单提交逻辑
				if (errors) {
					return
				}
				uni.showLoading({
					title: '修改中...',
					mask: true
				})

				// 是否启用功能的数据类型转换， 0 正常， 1 禁用
				if (typeof value.status === "boolean") {
					value.status = Number(!value.status)
				}


				// 使用 uni-clientDB 提交数据
				db.collection(dbCollectionName).where({
					_id: this.formDataId
				}).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateTo({
						url: '/pages/system/user/list'
					}), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName)
				.doc(id)
				.field('username,nickname,year,role,college,mobile,email,status')
				.get()
				.then((res) => {
					const data = res.result.data[0]
					console.log(res.result.data[0])
					if (data) {
						// Object.keys(this.formData).forEach(name => {
						// 	this.binddata(name, data[name])
						// })
						const status = data.status
						if (status < 2) {
							data.status = !status
							console.log(data)
							this.formData = data
						} else if (status === 2) {
							this.formData.status = '审核中'
						} else if (status === 3) {
							this.formData.status = '审核拒绝'
						} else {
							this.formData.status = '未知状态'
						}

					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			loadroles() {
				db.collection('uni-id-roles').limit(500).get().then(res => {
					const roleIds = []
					this.roles = res.result.data.map(item => {
						roleIds.push(item.role_id)
						return {
							value: item.role_id,
							text: item.role_name
						}
					})
					if (roleIds.indexOf('admin') === -1) {
						this.roles.unshift({
							value: 'admin',
							text: '超级管理员'
						})
					}
				}).catch(err => {
					uni.showModal({
						title: '提示',
						content: err.message,
						showCancel: false
					})
				})
			},
			loadcolleges(){
				db.collection('hr-college').limit(500).get().then(res => {
					this.colleges = res.result.data.map(item => {
						return {
							value: item.college_id,
							text: item.name
						}
					})
				}).catch(err => {
					uni.showModal({
						title: '提示',
						content: err.message,
						showCancel: false
					})
				})
			}
		}
	}
</script>
